package com.lagou.rocketmq.task.listener;

import com.alibaba.fastjson.JSON;
import com.lagou.rocketmq.task.constant.RedisKey;
import com.lagou.rocketmq.task.dao.OrderDao;
import com.lagou.rocketmq.task.dao.ProductDao;
import com.lagou.rocketmq.task.enumration.OrderStatusEnum;
import com.lagou.rocketmq.task.model.entity.OrderDO;
import com.lagou.rocketmq.task.model.event.CheckOrderPayEvent;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 超过时间未付款，检查订单状态，更新订单状态，回滚库存
 */
@Component
@RocketMQMessageListener(topic = "seckilling_check_pay_order", consumerGroup = "consumer_grp_02")
public class CheckOrderPayListener  implements RocketMQListener<String> {

  private static Logger logger = LoggerFactory.getLogger(CreateOrderListener.class);

  @Autowired
  private OrderDao orderDao;

  @Autowired
  private ProductDao productDao;

  @Autowired
  private JedisPool jedisPool;

  @Override
  public void onMessage(String message) {
    logger.info("接收到检查订单支付消息" + message);
    CheckOrderPayEvent checkOrderPayEvent = JSON.parseObject(message, CheckOrderPayEvent.class);
    Integer orderId = checkOrderPayEvent.getOrderId();
    OrderDO orderDO = orderDao.getOne(orderId);
    if (orderDO == null) {
      logger.info("订单不存在，消息：{}", message);
      return;
    }

    // 更新为未支付状态
    int count = orderDao.updateOrderStatusByStatus(orderId, OrderStatusEnum.NOT_PAY.getValue(), OrderStatusEnum.CANCEL.getValue());
    if (count <= 0) {
      return;
    }

    // 回滚库存
    String productInventoryKey = RedisKey.getProductInventoryKey(orderDO.getProductId());
    productDao.incrProductInventory(orderDO.getProductId());
    try (Jedis jedis = jedisPool.getResource()) {
      jedis.incr(productInventoryKey);
    }
  }
}
